package com.heima.comment.service.impl;

import com.heima.comment.service.WmCommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.WmCommentAddDTO;
import com.heima.model.wemedia.dtos.WmCommentDTO;
import com.heima.model.wemedia.dtos.WmTopDTO;
import com.heima.model.wemedia.pojos.WmCommentTop;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmCommentRepayVO;
import com.heima.model.wemedia.vos.WmCommentVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author:luoyong
 * Date:2021/12/5 16:46
 */
@Service
@Slf4j
public class WmCommentServiceImpl implements WmCommentService {
    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * @功能: 自媒体评论列表
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult commentHand(WmCommentDTO dto) {
        //1.校验参数
        if (dto == null || dto.getIndex() == null || dto.getSize() == null) {
            log.error("自媒体查询评论参数错误");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "自媒体查询评论参数错误");
        }
        //2.判断用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            log.error("自媒体用户未登录");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.通过 wm_user_id 查询 ap_author 表 查询 出 ap_author_id
        ResponseResult<List<Long>> result = articleFeign.findByVmUserId(user.getId());
        if (result.getCode() != 0) {
            log.warn("远程调用articleFeign的 findByVmUserId  出错");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用articleFeign的 findByVmUserId  出错");
        }
        //根据作者ID查询出文章ID
        List<Long> articleIds = result.getData();
        if (CollectionUtils.isEmpty(articleIds)) {
            log.warn("远程调用articleFeign的 findByVmUserId 找不到作者信息");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用articleFeign的 findByVmUserId 找不到作者信息");
        }
        //4.根据 ap_author_id 查询出 mongo 中 ap_comment 和 ap_comment_repay  分页  按时间降序
        Integer currentPage = (dto.getIndex() - 1) * dto.getSize();
        List<ApComment> apCommentList = mongoTemplate.find(Query.query(Criteria.where("articleId").in(articleIds))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .skip(currentPage).limit(dto.getSize()), ApComment.class);

        if (CollectionUtils.isEmpty(apCommentList)) {
            log.info("该用户的文章没有评论");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该用户的文章没有评论");
            return null;
        }
        List<WmCommentVO> wmCommentVOS = new ArrayList<>();
        for (ApComment apComment : apCommentList) {
            WmCommentVO wmCommentVO = new WmCommentVO();
            wmCommentVO.setId(apComment.getId());
            wmCommentVO.setAdmireNum(apComment.getLikes()); //点赞数
            wmCommentVO.setAvatarUrl("https://hmleadnews-ly.oss-cn-shanghai.aliyuncs.com" +
                    "/material/2021/12/20211202/e87f7a391fe246449ef7abb47a587d7a.jpg");   //头像
            wmCommentVO.setContent(apComment.getContent()); //评论
            wmCommentVO.setDate(apComment.getCreatedTime()); //评论时间

            //查询wm_user 得到 用户昵称
            String authorName = apComment.getAuthorName();
            ResponseResult<WmUser> result1 = wemediaFeign.findByName(authorName);
            if (result1.getCode() != 0) {
                log.warn("远程调用wemediaFeign的 findByName  出错");
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用wemediaFeign的 findByName  出错");
            }
            WmUser wmUser1 = result1.getData();
            wmCommentVO.setNickName(wmUser1.getNickname()); // 昵称
            wmCommentVO.setReplyNum(apComment.getReply()); //评论数

            //封装回复信息
            List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(Query.query(Criteria.
                    where("commentId").is(apComment.getId())), ApCommentRepay.class);
            log.info("自媒体评论管理 查询评论回复了~~~");

            List<WmCommentRepayVO> wmCommentRepayVOS = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(apCommentRepayList)) {
                for (ApCommentRepay apCommentRepay : apCommentRepayList) {
                    WmCommentRepayVO wmCommentRepayVO = new WmCommentRepayVO();
                    wmCommentRepayVO.setContent(apCommentRepay.getContent());
                    //查询wm_user 得到 用户昵称
                    String authorName1 = apCommentRepay.getAuthorName();
                    ResponseResult<WmUser> result2 = wemediaFeign.findByName(authorName1);
                    if (result2.getCode() != 0) {
                        log.warn("远程调用wemediaFeign的 findByName  出错");
                        CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用wemediaFeign的 findByName  出错");
                    }
                    WmUser wmUser2 = result1.getData();
                    wmCommentRepayVO.setNickName(wmUser2.getNickname());
                    wmCommentRepayVOS.add(wmCommentRepayVO);
                }
            }
            //封装VmCommentRepay对象    封装VmCommentVO对象
            //5.处理结果
            wmCommentVO.setReplies(wmCommentRepayVOS);
            wmCommentVOS.add(wmCommentVO);
        }
        return ResponseResult.okResult(wmCommentVOS);
    }

    /**
     * @功能: 自媒体评论置顶
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult commentChangeTop(String id) {
        //1.校验参数
        if (StringUtils.isBlank(id)) {
            log.info("无效评论ID参数~~~");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            log.error("用户没登录，无法置顶");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.修改状态 并 修改 app 端评论列表
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(id)), ApComment.class);
        if (apComment != null) {
            if (apComment.getFlag() == 3) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "不能重复置顶评论");
            }
            log.info("置顶查询评论成功");

            List<WmCommentTop> wmCommentTops = mongoTemplate.find(Query.query(Criteria.where("wmUserId")
                    .is(user.getId())), WmCommentTop.class);
            if (wmCommentTops.size() < 4) {
                WmCommentTop top = new WmCommentTop();
                top.setWmUserId(user.getId());
                top.setCreatedTime(new Date());
                mongoTemplate.save(top);
                apComment.setFlag((short) 3);
                mongoTemplate.save(apComment);
            } else {
                log.error("只能置顶3个评论");
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "只能置顶3个评论");
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * @功能: 自媒体评论回复
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult commentAddHand(WmCommentAddDTO dto) {
        //检查参数
        if(dto == null || dto.getId()==null||dto.getContent()==null){
            log.error("参数出错，无法回复评论");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数出错，无法回复评论");
        }
        //判断用户有没有登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            log.error("用户没登录，无法回复");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        ResponseResult<WmUser> result = wemediaFeign.findById(user.getId());
        if (result.getCode() != 0) {
            log.error("远程调用 wemediaFeign的findById方法出错");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();
        if (wmUser == null) {
            log.error("自媒体用户不存在，无法回复");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "自媒体用户不存在，无法回复");
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getId());
        apCommentRepay.setAuthorId(wmUser.getApUserId());
        apCommentRepay.setAuthorName(wmUser.getName());
        //新增评论回复
        mongoTemplate.save(apCommentRepay);
        log.info("评论回复成功~~~~~~");
        return null;
    }

    /**
     * @功能: 自媒体评论点赞
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult commentLikings(WmTopDTO dto) {
        //校验参数
        //1.校验参数
        if (dto == null || dto.getId() == null) {
            log.info("无效评论ID参数~~~");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.通过用户ID  1102 查询到 作者ID  5
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            log.error("用户没登录，无法点赞");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        ResponseResult<WmUser> result = wemediaFeign.findById(user.getId());
        if (result.getCode() != 0) {
            log.error("远程调用 wemediaFeign的findById方法出错");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();
        if (wmUser == null) {
            log.error("自媒体用户不存在，无法点赞");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "自媒体用户不存在，无法点赞");
        }
        //新增回复点赞  评论ID 作者ID 不能重复点赞
        ApCommentLike commentLike = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(wmUser.getApUserId())
                .and("commentId").is(dto.getId())), ApCommentLike.class);
        if (commentLike == null) {
            //没有 直接保存插入
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(dto.getId());
            apCommentLike.setAuthorId(wmUser.getApUserId());
            apCommentLike.setOperation((short) 0);
            mongoTemplate.save(apCommentLike);
            log.info("自媒体评论管理评论点赞成功~~~~~~~~");
        } else {
            log.error("不能重复点赞");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "不能重复点赞");
        }
        //更新评论里的点赞数
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(dto.getId())), ApComment.class);
        Integer likes = apComment.getLikes();
        apComment.setLikes(likes+1);
        mongoTemplate.save(apComment);
        log.info("评论点赞成功~~~");
        return ResponseResult.okResult();
    }

    /**
     * @功能: 自媒体评论删除
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult commentdeleteHand(String id) {
        //判断参数
        if (id== null) {
            log.info("无效评论ID参数~~~");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        log.info(id);
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(id)), ApComment.class);
        if (apComment == null) {
            log.error("该评论不存在，无法删除");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "该评论不存在，无法删除");
        }
        //根据评论ID查出回复ID列表
        List<ApCommentRepay> commentRepays = mongoTemplate.find(Query.query(Criteria
                .where("commentId").is(id)), ApCommentRepay.class);
        //删除评论相关的回复
        if (CollectionUtils.isNotEmpty(commentRepays)) {
            for (ApCommentRepay commentRepay : commentRepays) {
                //查询评论回复相关的点赞
                List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(Query.query(Criteria
                        .where("commentRepayId").is(commentRepay.getId())), ApCommentRepayLike.class);
                if (CollectionUtils.isNotEmpty(apCommentRepayLikes)) {
                    //删除评论回复相关的点赞
                    for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                        mongoTemplate.remove(apCommentRepayLike);
                    }
                }
                //删除评论相关的回复
                mongoTemplate.remove(commentRepay);
            }
        }
        //删除评论相关的点赞
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(Query
                .query(Criteria.where("commentId").is(id)), ApCommentLike.class);
        if (CollectionUtils.isNotEmpty(apCommentLikes)) {
            for (ApCommentLike apCommentLike : apCommentLikes) {
                mongoTemplate.remove(apCommentLike);
            }
        }
        //删除评论
        mongoTemplate.remove(apComment);
        log.info("删除评论相关点赞、相关回复点赞、相关回复、评论成功~~~~~");
        return ResponseResult.okResult();
    }
}
